package cc.comac.mom.datahandlers.entity;

import java.math.BigDecimal;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cc.comac.mom.bean.*;
import cc.comac.mom.util.MomConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cc.comac.mom.bean.base.LimitPageBean;
import cc.comac.mom.dao.entity.EquipBenchmarkItemDao;
import cc.comac.mom.dao.entity.EquipDevDao;
import cc.comac.mom.dao.entity.EquipMaintainWorkOrderDao;
import cc.comac.mom.dao.entity.EquipMaintainWorkOrderExecutionDao;
import cc.comac.mom.dao.entity.QualityAttachmentGroupDao;
import cc.comac.mom.entity.EquipBenchmarkItemEntity;
import cc.comac.mom.entity.EquipDevEntity;
import cc.comac.mom.entity.EquipDevHistoryEntity;
import cc.comac.mom.entity.EquipMaintainWorkOrderEntity;
import cc.comac.mom.entity.EquipMaintainWorkOrderExecutionEntity;
import cc.comac.mom.entity.QualityAttachmentGroupEntity;
import cc.comac.mom.util.BaseEntityDataUtil;
import cc.comac.mom.util.ResultBean;
import cc.comac.mom.util.TimeUtil;

@Component
@Transactional
public class EquipMaintainWorkOrderExecutionDataHandler
		extends ServiceImpl<EquipMaintainWorkOrderExecutionDao, EquipMaintainWorkOrderExecutionEntity> {

	@Autowired
	private EquipMaintainWorkOrderExecutionDao equipMaintainWorkOrderExecutionDao;

	@Autowired
	private EquipMaintainWorkOrderDao equipMaintainWorkOrderDao;

	@Autowired
	private BaseEntityDataUtil baseEntityDataUtil;

	@Autowired
	private EquipBenchmarkItemDao equipBenchmarkItemDao;
	@Autowired
	private QualityAttachmentGroupDataHandler qualityAttachmentGroupDataHandler;

	@Autowired
	private QualityAttachmentGroupDao qualityAttachmentGroupDao;

	@Autowired
	private EquipDevHistoryDataHandler equipDevHistoryDataHandler;

	@Autowired
	private EquipDevDao equipDevDao;
	// 新增保养基准执行数据
	public ResultBean insertMaintainWorkOrderExecution(
			EquipMaintainWorkOrderExecution equipMaintainWorkOrderExecution) {
		ResultBean resultBean = new ResultBean(true);
		EquipMaintainWorkOrderExecutionEntity innerData = equipMaintainWorkOrderExecution.getInnerData();
		if (innerData != null) {
			baseEntityDataUtil.setBaseEntityData(innerData);
			equipMaintainWorkOrderExecutionDao.insert(innerData);
		}
		return resultBean;
	}

	// 批量新增保养基准执行数据
	public ResultBean batchInsertMaintainWorkOrderExecution(
			List<EquipMaintainWorkOrderExecution> equipMaintainWorkOrderExecutionList) {
		ResultBean resultBean = new ResultBean(true);
		List<EquipMaintainWorkOrderExecutionEntity> entityList = new ArrayList<EquipMaintainWorkOrderExecutionEntity>();
		for (EquipMaintainWorkOrderExecution equipMaintainWorkOrderExecution : equipMaintainWorkOrderExecutionList) {
			EquipMaintainWorkOrderExecutionEntity innerData = equipMaintainWorkOrderExecution.getInnerData();
			baseEntityDataUtil.setBaseEntityData(innerData);
			entityList.add(equipMaintainWorkOrderExecution.getInnerData());
		}
		if (entityList.size() > 0) {
			saveBatch(entityList, entityList.size());
		}
		return resultBean;
	}

	// 更新保养基准执行数据
	public ResultBean updateMaintainWorkOrderExecution(
			EquipMaintainWorkOrderExecution equipMaintainWorkOrderExecution) {
		ResultBean resultBean = new ResultBean(true);
		EquipMaintainWorkOrderExecutionEntity innerData = equipMaintainWorkOrderExecution.getInnerData();
		if (innerData.getId() == 0) {
			throw new RuntimeException("无法获取数据主键");
		}
		if (innerData.getBenchmarkId() == 0) {
			throw new RuntimeException("无法获取基准主键");
		}
		if (innerData.getBenchmarkItemId() == 0) {
			throw new RuntimeException("无法获取基准详情主键");
		}
		if (innerData.getMaintainWorkOrderId() == 0) {
			throw new RuntimeException("无法获取保养工单主键");
		}
		baseEntityDataUtil.updateBaseEntityData(innerData);
		// 更新保养基准对应数据
		equipMaintainWorkOrderExecutionDao.updateById(innerData);
		List<Long> attachmentIds = innerData.getAttachmentIds();
		if (attachmentIds.size() > 0) {
			QueryWrapper<QualityAttachmentGroupEntity> queryWrapper = new QueryWrapper<QualityAttachmentGroupEntity>();
			queryWrapper.eq("row_status", 1);
			queryWrapper.eq("group_id", innerData.getPictureAttachmentGroupId());
			qualityAttachmentGroupDao.delete(queryWrapper);

			List<QualityAttachmentGroup> attachGroupList = new ArrayList<QualityAttachmentGroup>();
			for (Long attachmentId : attachmentIds) {
				QualityAttachmentGroup qualityAttachmentGroup = new QualityAttachmentGroup();
				QualityAttachmentGroupEntity qualityAttachmentGroupEntity = new QualityAttachmentGroupEntity();
				qualityAttachmentGroup.setInnerData(qualityAttachmentGroupEntity);
				qualityAttachmentGroupEntity.setAttachmentId(attachmentId);
				qualityAttachmentGroupEntity.setGroupId(innerData.getPictureAttachmentGroupId());
				qualityAttachmentGroupEntity.setGroupName(innerData.getMaintainWorkOrderNumber());
				baseEntityDataUtil.setBaseEntityData(qualityAttachmentGroupEntity);
				attachGroupList.add(qualityAttachmentGroup);
			}
			// 新增附件数据
			qualityAttachmentGroupDataHandler.insertBatch(attachGroupList);
		}

		return resultBean;
	}

	// 查询保养基准执行数据
	public ResultBean selectByOrderId(EquipMaintainWorkOrderExecution equipMaintainWorkOrderExecution) {
		ResultBean resultBean = new ResultBean(true);
		if (equipMaintainWorkOrderExecution.getPageSize() == 0) {
			equipMaintainWorkOrderExecution.setPageSize(10);
		}
		if (equipMaintainWorkOrderExecution.getPageNum() == 0) {
			equipMaintainWorkOrderExecution.setPageNum(1);
		}
		EquipMaintainWorkOrderExecutionEntity innerData = equipMaintainWorkOrderExecution.getInnerData();
		if (innerData.getMaintainWorkOrderId() == 0) {
			throw new RuntimeException("无法获取工单主键");
		}
		// 查询工单对应的基准工单
		QueryWrapper<EquipMaintainWorkOrderExecutionEntity> queryWrapper = new QueryWrapper<EquipMaintainWorkOrderExecutionEntity>();
		queryWrapper.eq("row_status", 1);
		queryWrapper.eq("maintain_work_order_id", innerData.getMaintainWorkOrderId());
		Page<EquipMaintainWorkOrderExecutionEntity> page = new Page<EquipMaintainWorkOrderExecutionEntity>(
				equipMaintainWorkOrderExecution.getPageNum(), equipMaintainWorkOrderExecution.getPageSize());
		IPage<EquipMaintainWorkOrderExecutionEntity> selectPage = equipMaintainWorkOrderExecutionDao.selectPage(page,
				queryWrapper);
		List<EquipMaintainWorkOrderExecutionEntity> selectList = selectPage.getRecords();
		if (selectList.size() > 0) {
			// 获取基准详情主键
			List<Long> benchmarkList = new ArrayList<Long>();
			for (EquipMaintainWorkOrderExecutionEntity equipMaintainWorkOrderExecutionEntity : selectList) {
				benchmarkList.add(equipMaintainWorkOrderExecutionEntity.getBenchmarkItemId());
			}
			// 通过基准详情主键查询基准详情
			List<EquipBenchmarkItemEntity> selectBatchIds = equipBenchmarkItemDao.selectBatchIds(benchmarkList);
			// 将基准详情中的数据赋值到工单执行的表中
			for (EquipMaintainWorkOrderExecutionEntity equipMaintainWorkOrderExecutionEntity : selectList) {
				for (EquipBenchmarkItemEntity equipBenchmarkItemEntity : selectBatchIds) {
					if (equipMaintainWorkOrderExecutionEntity.getBenchmarkItemId() == equipBenchmarkItemEntity
							.getId()) {
						equipMaintainWorkOrderExecutionEntity
								.setBenchmarkItemName(equipBenchmarkItemEntity.getItemName());
						equipMaintainWorkOrderExecutionEntity.setRecord(equipBenchmarkItemEntity.getRecord());
						equipMaintainWorkOrderExecutionEntity
								.setBenchmarkItemStandard(equipBenchmarkItemEntity.getItemStandard());
						equipMaintainWorkOrderExecutionEntity
								.setBenchmarkItemMethod(equipBenchmarkItemEntity.getItemMethod());
						equipMaintainWorkOrderExecutionEntity.setBenchmarkDevPart(equipBenchmarkItemEntity.getBenchmarkDevPart());
						equipMaintainWorkOrderExecutionEntity
								.setBenchmarkResultType(equipBenchmarkItemEntity.getResultType());
						equipMaintainWorkOrderExecutionEntity
								.setBenchmarkStandardValue(equipBenchmarkItemEntity.getStandardValue());
						equipMaintainWorkOrderExecutionEntity
								.setBenchmarkType(equipBenchmarkItemEntity.getBenchmarkType());
						equipMaintainWorkOrderExecutionEntity
								.setBenchmarkDeviceShutdown(equipBenchmarkItemEntity.getDeviceShutdown());
						equipMaintainWorkOrderExecutionEntity
								.setBenchmarkTime(equipBenchmarkItemEntity.getBenchmarkTime());
						if (equipMaintainWorkOrderExecutionEntity.getPictureAttachmentGroupId() != 0) {
							List<QualityAttachmentGroup> byAttachmentGroupId = qualityAttachmentGroupDataHandler
									.getByAttachmentGroupId(equipMaintainWorkOrderExecutionEntity.getPictureAttachmentGroupId());
							equipMaintainWorkOrderExecutionEntity.setListAttachmentGroup(byAttachmentGroupId);
						}
					}
				}
			}
		}
		LimitPageBean<EquipMaintainWorkOrderExecutionEntity> of = (LimitPageBean<EquipMaintainWorkOrderExecutionEntity>) LimitPageBean
				.of(selectPage);
		resultBean.setObject(of);
		return resultBean;
	}

	// 查询保养工单执行数据
	public ResultDev selectByCondition(EquipMaintainWorkOrderBean obj) {

		ResultDev resultDev = new ResultDev();
		if (obj.getPageSize() == 0) {
			obj.setPageSize(10);
		}
		obj.setPageNum((obj.getPageNum()-1)*obj.getPageSize());
		if(obj.getStatusList()==null){
			obj.setStatusList(new ArrayList<>());
			obj.getStatusList().add(MomConstants.EQUIP_MAINTAIN_ORDER_STATUS_NOEXECUTE);
			obj.getStatusList().add(MomConstants.EQUIP_MAINTAIN_ORDER_STATUS_EXECUTEING);
		}
		List<EquipMaintainWorkOrderBean> list = equipMaintainWorkOrderDao.selectByFields(obj);
		long countByFields = equipMaintainWorkOrderDao.selectCountByFields(obj);

		// 将查询总数除以每页数量后向上取整获取总页数
		double pageCount = Math.ceil((double)countByFields / obj.getPageSize());
		resultDev.setEntityList(list);
		resultDev.setPageCount((int)pageCount);
		resultDev.setTotalQuantity((int)countByFields);
		return resultDev;
	}

	// 开始执行按钮
	public ResultBean startExecution(EquipMaintainWorkOrderExecution equipMaintainWorkOrderExecution) {
		ResultBean resultBean = new ResultBean(true);
		EquipMaintainWorkOrderExecutionEntity innerData = equipMaintainWorkOrderExecution.getInnerData();
		if (innerData.getMaintainWorkOrderId() == 0) {
			throw new RuntimeException("无法获取工单数据主键！");
		}
		// 通过主键id查询工单基准数据并更新数据
		QueryWrapper<EquipMaintainWorkOrderExecutionEntity> queryWrapper = new QueryWrapper<EquipMaintainWorkOrderExecutionEntity>();
		queryWrapper.eq("row_status", 1);
		queryWrapper.eq("maintain_work_order_id", innerData.getMaintainWorkOrderId());
		List<EquipMaintainWorkOrderExecutionEntity> selectList = equipMaintainWorkOrderExecutionDao
				.selectList(queryWrapper);
		if (selectList.size() > 0) {
			for (EquipMaintainWorkOrderExecutionEntity equipMaintainWorkOrderExecutionEntity : selectList) {
				equipMaintainWorkOrderExecutionEntity.setPlanFirstActualStartTime(TimeUtil.getLocalDate());
				baseEntityDataUtil.updateBaseEntityData(equipMaintainWorkOrderExecutionEntity);
				if (equipMaintainWorkOrderExecutionEntity.getId() == innerData.getId()) {
					equipMaintainWorkOrderExecutionEntity.setOrderBenchmarkItemStartTime(TimeUtil.getLocalDate());
				}
			}
			this.updateBatchById(selectList, selectList.size());
		}

		// 通过工单主表主键查询工单数据并更新主表中的实际开始时间
		EquipMaintainWorkOrderEntity selectById = equipMaintainWorkOrderDao
				.selectById(innerData.getMaintainWorkOrderId());
		selectById.setFirstPlanActualDateStart(TimeUtil.getLocalDate());
		selectById.setExecutionUser(baseEntityDataUtil.getCurrentUser());
		selectById.setJobNumber(baseEntityDataUtil.getJobNumber());
		selectById.setStatus(MomConstants.EQUIP_MAINTAIN_ORDER_STATUS_EXECUTEING);
		baseEntityDataUtil.updateBaseEntityData(selectById);
		equipMaintainWorkOrderDao.updateById(selectById);
		Map<String, Object> returnMap = new HashMap<String, Object>();
		returnMap.put("executionTime", TimeUtil.getLocalDate());
		returnMap.put("executionTime", null);

		// 记录设备履历数据
		EquipDevHistory equipDevHistory = new EquipDevHistory();
		EquipDevHistoryEntity equipDevHistoryEntity = new EquipDevHistoryEntity();
		equipDevHistory.setInnerData(equipDevHistoryEntity);
		// 通过设备编号查询设备信息
		QueryWrapper<EquipDevEntity> queryWrapper2 = new QueryWrapper<EquipDevEntity>();
		queryWrapper2.eq("row_status", 1);
		queryWrapper2.eq("dev_number", selectById.getDevNumber());
		EquipDevEntity selectOne = equipDevDao.selectOne(queryWrapper2);
		equipDevHistoryEntity.setDevId(selectOne.getId());
		equipDevHistoryEntity.setDevNumber(selectOne.getDevNumber());
		equipDevHistoryEntity.setOperationDetail(selectById.getOrderNumber());
		equipDevHistoryEntity.setOperationStyle("保养");
		equipDevHistoryEntity.setOperator(baseEntityDataUtil.getCurrentUser());
		baseEntityDataUtil.setBaseEntityData(equipDevHistoryEntity);
		equipDevHistoryDataHandler.insertHistory(equipDevHistory);
		return resultBean;
	}

	// 执行按钮
	public ResultBean executionBenchmark(EquipMaintainWorkOrderExecution equipMaintainWorkOrderExecution) {
		ResultBean resultBean = new ResultBean(true);
		EquipMaintainWorkOrderExecutionEntity innerData = equipMaintainWorkOrderExecution.getInnerData();
		if (innerData.getId() == 0) {
			throw new RuntimeException("无法获取当前执行数据");
		}
		// 查询数据并更新执行的对应数据
		EquipMaintainWorkOrderExecutionEntity selectById = equipMaintainWorkOrderExecutionDao
				.selectById(innerData.getId());
		//Date orderBenchmarkItemStartTime = selectById.getOrderBenchmarkItemStartTime();
		selectById.setOrderBenchmarkItemEndTime(TimeUtil.getLocalDate());
		//String subDate = TimeUtil.subDate(orderBenchmarkItemStartTime, TimeUtil.getLocalDate());
		//selectById.setExecutionDuration(subDate + "时");
		selectById.setOrderBenchmarkItemActualValue(innerData.getOrderBenchmarkItemActualValue());
		selectById.setExecutionStatus("1");
		selectById.setExecutionResult(innerData.getExecutionResult());
		selectById.setAbnormalDescription(innerData.getAbnormalDescription());
		selectById.setPictureAttachmentGroupId(equipMaintainWorkOrderExecution.getInnerData().getPictureAttachmentGroupId());
		baseEntityDataUtil.updateBaseEntityData(selectById);
		equipMaintainWorkOrderExecutionDao.updateById(selectById);
		// 当下一个基准数据主键存在时更新下一个数据的开始时间
		if (innerData.getNextId() != 0 && innerData.getId() != innerData.getNextId()) {
			EquipMaintainWorkOrderExecutionEntity selectById2 = equipMaintainWorkOrderExecutionDao
					.selectById(innerData.getNextId());
			selectById2.setOrderBenchmarkItemStartTime(TimeUtil.getLocalDate());
			baseEntityDataUtil.updateBaseEntityData(selectById2);
			equipMaintainWorkOrderExecutionDao.updateById(selectById2);
		}

		//获取定检工单信息
		EquipMaintainWorkOrderEntity maintainWorkOrderEntity = equipMaintainWorkOrderDao.selectById(selectById.getMaintainWorkOrderId());
		Duration duration = Duration.between(TimeUtil.fomatDateToLocalDateTime(maintainWorkOrderEntity.getFirstPlanActualDateStart()),TimeUtil.getLocalDateTime());
		long hours = duration.toHours();
		maintainWorkOrderEntity.setActualExecuteTime(new BigDecimal(hours));

		QueryWrapper<EquipMaintainWorkOrderExecutionEntity> queryWrapper2 = new QueryWrapper<EquipMaintainWorkOrderExecutionEntity>();
		queryWrapper2.eq("row_status", 1);
		queryWrapper2.eq("maintain_work_order_id",innerData.getMaintainWorkOrderId());
		queryWrapper2.eq("execution_status", 0);
		int count=equipMaintainWorkOrderExecutionDao.selectCount(queryWrapper2);
		if(count==0){
			//设置工单执行完成
			maintainWorkOrderEntity.setStatus(MomConstants.EQUIP_MAINTAIN_ORDER_STATUS_EXECUTED);//执行完成
		}
		int updateById2 = equipMaintainWorkOrderDao.updateById(maintainWorkOrderEntity);
		if(updateById2<1) {
			throw new RuntimeException("修改保养工单执行状态失败");
		}
		return resultBean;
	}
}
